import { useMemo, useRef, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, Empty, Space, Table } from 'antd';

import { store } from '@/store';

import { usePermission } from '@/auth';
import { NumBool } from '@/enum';
import { roleUpdate } from '@/services/base/jiaoseguanlijiaosexiangguanjiekou';
import {
  permissionFrontGetByRoleId,
  permissionFrontGetTreeByRoleId,
  permissionFrontTree
} from '@/services/base/quanxianmokuaiqianduanyemianquanxianguanli';
import { Icon } from '@iconify/react/dist/iconify.js';

export type BizObject = BASE.RoleDataPermission;

export type AuthProps = {
  role?: BASE.Role;
};

// 获取当前节点下的所有子节点的key
function getChildAllKeys(data: BASE.PagePermissionVO): string[] {
  let res: string[] = [];

  res.push(data.permissionCode as string);

  if (data.child) {
    data.child.forEach((item) => {
      res = res.concat(getChildAllKeys(item));
    });
  }

  return res;
}

const Auth: React.FC<AuthProps> = ({ role }) => {
  const permission = usePermission();
  const allKeys = useRef<string[]>([]);
  const dict = useRef<
    Record<
      string,
      {
        parentKeys: string[];
        childKeys: string[];
      }
    >
  >({});
  const tree = useRequest(async () => {
    allKeys.current = [];
    dict.current = {};

    const res = await permissionFrontTree({
      queryApi: NumBool.否
    });

    const list = res.data || [];

    const flat = (list: BASE.PagePermissionVO[], parentKeys: string[] = []): string[] => {
      const keys: string[] = [];

      list.forEach((item) => {
        keys.push(item.permissionCode as string);
        dict.current[item.permissionCode] = {
          parentKeys,
          childKeys: getChildAllKeys(item)
        };
      });

      allKeys.current = [...allKeys.current, ...keys];

      return keys.concat(
        ...list.map((item) => flat(item.child || [], [...parentKeys, item.permissionCode]))
      );
    };

    flat(list);
    setExpandedRowKeys(allKeys.current);

    return list;
  });
  const roleAuth = useRequest(
    async () => {
      if (!role?.id) {
        return;
      }

      return (
        await permissionFrontGetByRoleId({ id: role.id } as unknown as ArgumentsType<
          typeof permissionFrontGetTreeByRoleId
        >[0])
      ).data;
    },
    {
      onSuccess: (res) => {
        setSelectedRowKeys([]);
        if (res) {
          setSelectedRowKeys(res.map((item) => item.permissionCode as unknown as string));
        }
      },
      refreshDeps: [role?.id]
    }
  );
  // 保存
  const save = useRequest(
    async () => {
      let permissionCodes: string[] = [];

      selectedRowKeys.forEach((key) => {
        permissionCodes.push(key);
        const parentKeys = dict.current[key].parentKeys;
        permissionCodes = permissionCodes.concat(parentKeys);
      });

      permissionCodes = Array.from(new Set(permissionCodes));

      await roleUpdate({
        ...role!,
        permissionCodes
      });

      store.app?.message.success('保存成功');
    },
    {
      manual: true
    }
  );
  const [_, setSelectedRowKeys] = useState<string[]>([]);
  const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([]);

  if (!role) {
    return <Empty description="请选择角色" />;
  }

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const selectedRowKeys = useMemo(() => {
    return _.filter((v) => {
      const child = dict.current[v];

      if (!child || child.childKeys.length <= 1) {
        return true;
      }

      return child.childKeys.every((key) => _.includes(key));
    });
  }, [_]);

  return (
    <>
      <Table<BASE.PagePermissionVO>
        title={() => {
          return (
            <>
              <Space>
                <Button
                  onClick={save.run}
                  disabled={tree.loading || save.loading}
                  loading={save.loading}
                  icon={<Icon icon="ri:save-fill" />}
                  type="primary"
                >
                  保存
                </Button>

                <Button onClick={setExpandedRowKeys.bind(null, allKeys.current)}>展开全部</Button>

                <Button onClick={setExpandedRowKeys.bind(null, [])}>收起全部</Button>
              </Space>
            </>
          );
        }}
        rowKey="permissionCode"
        rowSelection={{
          checkStrictly: false,
          selectedRowKeys,
          onChange: (keys) => {
            setSelectedRowKeys(keys as string[]);
          }
        }}
        bordered
        expandable={{
          expandedRowKeys,
          onExpandedRowsChange: (keys) => {
            setExpandedRowKeys(keys as string[]);
          },
          childrenColumnName: 'child'
        }}
        columns={[
          {
            title: '权限名称',
            dataIndex: 'permissionName'
          },
          {
            title: '权限编码',
            dataIndex: 'permissionCode'
          }
        ]}
        dataSource={tree.data}
        pagination={false}
        size="small"
        scroll={{
          x: 'max-content'
        }}
      />
    </>
  );
};

export default Auth;
